﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using System.Management;
using System.Configuration;

namespace Restart.Service
{
    // NOTE: If you change the class name "WcfService" here, you must also update the reference to "WcfService" in App.config.
    public class WcfService : IWcfService
    {
        public void Restart(string password)
        {
            if (this.IsPasswordValid(password)) this.CallWin32Shutdown("2");
        }

        public void Shutdown(string password)
        {
            if (this.IsPasswordValid(password)) this.CallWin32Shutdown("1");
        }

        private bool IsPasswordValid(string password)
        {
            if (string.Equals(System.Configuration.ConfigurationManager.AppSettings.GetValues("Password"), password))
                return true;

            return false;
        }

        private void CallWin32Shutdown(string flags)
        {
            ManagementBaseObject mboShutdown = null;
            ManagementClass mcWin32 = new ManagementClass("Win32_OperatingSystem");
            mcWin32.Get();
            // You can't shutdown without security privileges
            mcWin32.Scope.Options.EnablePrivileges = true;
            ManagementBaseObject mboShutdownParams = mcWin32.GetMethodParameters("Win32Shutdown");
            // Flag 1 means we want to shut down the system, 2 means restart.
            mboShutdownParams["Flags"] = flags;
            mboShutdownParams["Reserved"] = "0";
            foreach (ManagementObject manObj in mcWin32.GetInstances())
            {
                mboShutdown = manObj.InvokeMethod("Win32Shutdown", mboShutdownParams, null);
            }
        }


    }
}
